package com.cloud.gateway.common;

import com.alibaba.fastjson.JSONObject;
import com.cloud.gateway.domain.ServiceResult;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class Common {

    public static Mono<Void> jsonReturn(ServerWebExchange exchange,ServiceResult serviceResult)
    {
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        serverHttpResponse.setStatusCode(HttpStatus.OK);
        byte[] bits = JSONObject.toJSONString(serviceResult).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        return serverHttpResponse.writeWith(Mono.just(buffer));
    }
}
